<template>
  <div class="topology-canvas" @drop="onDrop" @click="onCanvasClick">
    <VueFlow
      :nodes="nodes"
      :edges="edges"
      :node-types="nodeTypes"
      :fit-view-on-init="true"
      :select-nodes-on-drag="false"
      @dragover="onDragOver"
      @dragleave="onDragLeave"
      @nodes-change="emit('nodes-change', $event)"
      @edges-change="emit('edges-change', $event)"
      @node-click="onNodeClick"
      @edge-click="onEdgeClick"
      @connect="emit('connect', $event)"
    >
      <Background />
      <Controls>
        <!-- 自定义保存按钮 -->
        <button
          title="保存拓扑图"
          @click="onSave"
          class="vue-flow__controls-button"
          style="display: flex; align-items: center; justify-content: center"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"
            />
          </svg>
        </button>
      </Controls>
      <MiniMap />
    </VueFlow>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { VueFlow, useVueFlow } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import { Controls } from "@vue-flow/controls";
import { MiniMap } from "@vue-flow/minimap";

// 导入样式
import "@vue-flow/core/dist/style.css";
import "@vue-flow/core/dist/theme-default.css";
import "@vue-flow/controls/dist/style.css";
import "@vue-flow/minimap/dist/style.css";

const { screenToFlowCoordinate, addNodes, toObject  } = useVueFlow();

const props = defineProps({
  nodes: {
    type: Array,
    required: true,
  },
  edges: {
    type: Array,
    required: true,
  },
  selectedNodeType: {
    type: String,
    default: null,
  },
  nodeTypes: {
    type: String,
    default: null, // 使用 VueFlow 的默认节点类型
  },
});

const emit = defineEmits([
  "nodes-change",
  "edges-change",
  "node-click",
  "edge-click",
  "connect",
  "canvas-click",
]);

// 使用 props 的 nodes 和 edges
const nodes = ref([...props.nodes]);
const edges = ref([...props.edges]);

// 监听 props 变化
watch(
  () => props.nodes,
  (newNodes) => {
    nodes.value = [...newNodes];
  },
  { deep: true }
);

watch(
  () => props.edges,
  (newEdges) => {
    edges.value = [...newEdges];
  },
  { deep: true }
);

// 新增：保存功能
const onSave = () => {
  try {
    const flowData = toObject();
    const saveData = {
      ...flowData,
      savedAt: new Date().toISOString(),
      version: "1.0"
    };
    localStorage.setItem("missile-topology-save", JSON.stringify(saveData));
    console.log("拓扑图已保存:", saveData);
    
    // 可以添加用户提示
    alert("拓扑图保存成功！");
  } catch (error) {
    console.error("保存失败:", error);
    alert("保存失败，请重试");
  }
};

// 新增：画布点击事件
const onCanvasClick = (event) => {
  // 检查点击的是否是画布空白区域（不是节点、边、控制按钮等）
  const isBackgroundClick =
    event.target.classList.contains("vue-flow__background") ||
    event.target.classList.contains("topology-canvas") ||
    event.target.closest(".vue-flow__background");

  if (isBackgroundClick) {
    emit("canvas-click", event);
  }
};

// 修改：节点点击事件 - 转发给父组件
const onNodeClick = (event) => {
  emit("node-click", event);
};

// 修改：边点击事件 - 转发给父组件
const onEdgeClick = (event) => {
  emit("edge-click", event);
};

// 拖拽处理
const onDragOver = (event) => {
  event.preventDefault();
  event.dataTransfer.dropEffect = "move";
};

const onDragLeave = (event) => {
  // 可选：处理拖拽离开
};

const onDrop = (event) => {
  event.preventDefault();
  console.log("Drop event triggered");

  const nodeData = event.dataTransfer.getData("application/vueflow/node");

  if (nodeData) {
    const nodeTemplate = JSON.parse(nodeData);

    // 使用 VueFlow 的坐标转换
    const position = screenToFlowCoordinate({
      x: event.clientX,
      y: event.clientY,
    });

    // 动态计算节点尺寸和连接点
    const { nodeSize, handles } = calculateDynamicNodeConfig(nodeTemplate);

    // 创建新节点 - 使用动态计算的尺寸
    const newNode = {
      id: `${nodeTemplate.type}-${Date.now()}`,
      type: "missileDevice",
      position,
      data: {
        label: nodeTemplate.name,
        type: nodeTemplate.type,
        description: nodeTemplate.description,
        connectors: nodeTemplate.connectors,
        ...nodeTemplate.defaultData,
      },
      // 移除 style 中的 padding，使用动态计算的尺寸
      style: {
        border: `2px solid ${nodeTemplate.color}`,
        borderRadius: "8px",
        background: "white",
        width: `${nodeSize.width}px`,
        height: `${nodeSize.height}px`,
        fontSize: "11px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
      },
    };

    // 只做一件事：手动更新 nodes 并通知父组件
    const updatedNodes = [...nodes.value, newNode];
    nodes.value = updatedNodes;
    emit("nodes-change", updatedNodes);

    console.log("Node added with dynamic size:", newNode);
    console.log("Current nodes:", nodes.value);
  }
};

// 新增：动态计算节点配置的函数
function calculateDynamicNodeConfig(nodeTemplate) {
  const allPins = getAllPins(nodeTemplate.connectors)
  
  // 计算尺寸 - 增加基础尺寸
  const baseWidth = 200 // 增加宽度
  const headerHeight = 45 // 头部高度
  const connectorTitleHeight = 22 // 连接器标题高度
  const pinRowHeight = 24 // 增加针脚行高
  
  // 计算总高度
  let totalHeight = headerHeight
  
  nodeTemplate.connectors?.forEach(connector => {
    totalHeight += connectorTitleHeight // 连接器标题
    if (connector.pins && connector.pins.length > 0) {
      totalHeight += connector.pins.length * pinRowHeight
    }
  })
  
  // 增加底部边距
  totalHeight += 8
  
  // 确保最小高度，但对于针脚多的设备要足够大
  const minHeight = Math.max(140, totalHeight) // 动态最小高度
  
  return {
    nodeSize: {
      width: baseWidth,
      height: minHeight
    }
  }
}

// 新增：获取所有针脚
function getAllPins(connectors) {
  if (!connectors || !Array.isArray(connectors)) return [];

  const allPins = [];
  connectors.forEach((connector) => {
    if (connector.pins && Array.isArray(connector.pins)) {
      connector.pins.forEach((pin) => {
        allPins.push({
          ...pin,
          connectorId: connector.id, // 记录所属连接器
          fullId: `${connector.id}-${pin.id}`, // 完整ID：连接器-针脚
        });
      });
    }
  });

  return allPins;
}

// 新增：生成针脚连接点
function generatePinHandles(pins, headerHeight, rowHeight, padding) {
  const sourceHandles = [];
  const targetHandles = [];

  pins.forEach((pin, index) => {
    const handleConfig = {
      id: pin.fullId, // 使用完整ID作为连接点ID
      type: "default",
      position: "Left", // 暂时都放在左侧，后续可以根据方向调整
      style: {
        top: `${headerHeight + padding + index * rowHeight + rowHeight / 2}px`,
        left: "0px",
        width: "8px",
        height: "8px",
        background: getPinColor(pin.type),
        border: `1px solid ${getPinBorderColor(pin.type)}`,
        borderRadius: "2px",
      },
      data: {
        pinId: pin.id,
        pinName: pin.name,
        pinType: pin.type,
        direction: pin.direction,
        signal: pin.signal,
        connectorId: pin.connectorId,
      },
    };

    // 根据针脚方向分配到不同的 handles 数组
    if (pin.direction === "output" || pin.direction === "bidirectional") {
      sourceHandles.push(handleConfig);
    }
    if (pin.direction === "input" || pin.direction === "bidirectional") {
      targetHandles.push(handleConfig);
    }
  });

  return { sourceHandles, targetHandles };
}

// 新增：根据针脚类型获取颜色
function getPinColor(pinType) {
  const colorMap = {
    power: "#ff6b6b",
    ground: "#495057",
    data: "#339af0",
    analog: "#51cf66",
    bus: "#cc5de8",
    discrete: "#ff922b",
    ethernet: "#20c997",
    fiber: "#e599f7",
  };
  return colorMap[pinType] || "#868e96";
}

// 新增：根据针脚类型获取边框颜色
function getPinBorderColor(pinType) {
  const borderColorMap = {
    power: "#c92a2a",
    ground: "#212529",
    data: "#1864ab",
    analog: "#2b8a3e",
    bus: "#9c36b5",
    discrete: "#e67700",
    ethernet: "#0ca678",
    fiber: "#ae3ec9",
  };
  return borderColorMap[pinType] || "#495057";
}
</script>

<style scoped>
.topology-canvas {
  height: 100%;
  background: #fafafa;
  cursor: pointer; /* 添加光标样式表明可点击 */
}

/* 自定义保存按钮样式 */
:deep(.vue-flow__controls-button) {
  width: 32px;
  height: 32px;
  border: 1px solid #e2e8f0;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

/* 新增：边的选中样式 */
:deep(.edge-selected) {
  filter: drop-shadow(0 0 3px rgba(32, 128, 240, 0.5));
}

:deep(.vue-flow__edge.selected) {
  z-index: 1000;
}
</style>